//
//  CategoryViewController.m
//  FreeReading
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "CategoryViewController.h"
#import "MoreTableViewController.h"
#import "CityListVC.h"
#import "ImageButtonView.h"
#import "ImageButton.h"
@interface CategoryViewController ()

@property (nonatomic, strong) ImageButtonView *buttonView;
@property (nonatomic, strong) UIButton *locationButton;

@end

@implementation CategoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setSubviews];
    
}
#pragma mark - 处理数据
- (void)loadData
{
    
    // 判断网络状态
    AFNetworkReachabilityManager *net_manager = [AFNetworkReachabilityManager sharedManager];
    [net_manager startMonitoring];
    [net_manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"网络异常 请检查网络后再试" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                return ;
                
            }];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
    }];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    
    NSString *urlString = [NSString stringWithFormat:kEnjoyUrl, [EnjoyDataManager shareManager].cityCode];
    
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        // 是否显示类目
        NSString *isShowCategory = responseObject[@"data"][@"info"][@"show_category"];
        [EnjoyDataManager shareManager].showCategory = isShowCategory;
        
        // 判断是否显示类目列表
        if ([isShowCategory isEqualToString:@"Y"]) {
            
            [self addCategoryList];
        } else {
            
            [self.buttonView removeFromSuperview];
            
        }
        [self addLocationButton];
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
        
        NSString *message = [NSString stringWithFormat:@"%@", [error localizedDescription]];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            return ;
        }];
        
        [alert addAction:action];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }];
}
// 设置UI
- (void)setSubviews
{
    self.view.backgroundColor = [UIColor whiteColor];
    // titleView
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"分类";
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
    // UIBarButtonItem
    UIBarButtonItem *leftbarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-arrowleft"] style:(UIBarButtonItemStylePlain) target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = leftbarButton;

}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
     self.hidesBottomBarWhenPushed = YES;
     [self loadData];
    
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.locationButton removeFromSuperview];
    [self.buttonView removeFromSuperview];
}


#pragma mark - 返回上一页面
- (void)back:(UIBarButtonItem *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 添加分类
- (void)addCategoryList
{
    
    self.buttonView = [[ImageButtonView alloc] initWithFrame:CGRectMake(0, 100, kScreenWidth, 80)];
    for (UIView *view in self.buttonView.subviews) {
        if ([view isKindOfClass:[ImageButton class]]) {
            ImageButton *button = (ImageButton *)view;
            // 取消按下时图片的阴影效果
            button.adjustsImageWhenHighlighted = NO;
            [button addTarget:self action:@selector(didSelectButton:) forControlEvents:UIControlEventTouchUpInside];

        }
            }
    
    [self.view addSubview:self.buttonView];
    
  
    
    
}
// 添加定位按钮
- (void)addLocationButton
{
   
   static CGFloat minY = 0;
   static NSString *title = nil;
    // 根据是否显示类目列表 改变控件的位置
    if ([[EnjoyDataManager shareManager].showCategory isEqualToString:@"Y"]) {
        minY = 300;
    } else {
        minY = 100;
    }
    
    if ([EnjoyDataManager shareManager].cityName == nil) {
        title = @"未定位";
    } else {
    title = [NSString stringWithFormat:@"定位:%@", [EnjoyDataManager shareManager].cityName];
    }
    self.locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.locationButton.frame = CGRectMake((kScreenWidth - 100) / 2, minY, 100, 30);
    [self.locationButton setTitle:title forState:UIControlStateNormal];
    [self.locationButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [self.locationButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.locationButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.locationButton setBackgroundColor:[UIColor redColor]];
    self.locationButton.layer.cornerRadius = 10.0;
    [self.locationButton addTarget:self action:@selector(chooseCity:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.locationButton];

}

// 点击切换城市按钮触发方法
- (void)chooseCity:(UIButton *)button
{
    CityListVC *cityListVC = [[CityListVC alloc] init];
    [self.navigationController pushViewController:cityListVC animated:YES];
    
}

// 点击imageButton触发的方法
- (void)didSelectButton:(ImageButton *)button
{
    MoreTableViewController *moreVC = [[MoreTableViewController alloc] init];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:moreVC];
    naVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    switch (button.index) {
        case 0:
        {
            moreVC.url = [NSString stringWithFormat:kArtUrl, 1, [EnjoyDataManager shareManager].cityCode];
            moreVC.titles = @"演艺";
            break;
        }
        case 1:
        {
            moreVC.url = [NSString stringWithFormat:kArtUrl, 4, [EnjoyDataManager shareManager].cityCode];
            moreVC.titles = @"度假";
            
            break;
        }
        case 2:
        {
            moreVC.url = [NSString stringWithFormat:kMovieUrl,[EnjoyDataManager shareManager].cityCode];
            moreVC.titles = @"电影";
            break;
        }
        case 3:
        {
            moreVC.url = [NSString stringWithFormat:kArtUrl, 9, [EnjoyDataManager shareManager].cityCode];
            moreVC.titles = @"美食";
            NSLog(@"%s %d", __FUNCTION__, __LINE__);
            
            break;
        }
        case 4:
        {
            moreVC.url = [NSString stringWithFormat:kArtUrl, 3, [EnjoyDataManager shareManager].cityCode];
            moreVC.titles = @"活动";
            
            break;
        }
        default:
            break;
    }
    [self presentViewController:naVC animated:YES completion:nil];

}

#pragma mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if ([self isViewLoaded] && self.view.window == nil) {
        
        self.view = nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
